from pypdo.pdo import PDO


class Model(object):

    table = ""
    __pdo_connect = None
    debug = False

    '''
    config = {
            "host": "localhost",
            "user": "root",
            "password": "",
            "debug": False,
            "db": "test"
        }
    '''

    def __init__(self,**config):

        try:
            self.__pdo_connect = PDO(**config)

        except Exception as e:

            self.__exception(e)

    def __exception(self, e):

        raise Exception(e)

    def add(self, rows):

        try:
            last_insert_id = self.__pdo_connect.insert(self.table, rows)
            return last_insert_id
        except Exception as e:
            self.__exception(e)

    def delete(self, where):

        try:
            affect_rows = self.__pdo_connect.delete(self.table, where)
            return affect_rows
        except Exception as e:
            self.__exception(e)

    def update(self, update_data, where):
        try:
            affect_rows = self.__pdo_connect.update(self.table, update_data, where)
            return affect_rows
        except Exception as e:
            self.__exception(e)

    def get(self, where={}, order={}, cols=[]):
        try:
            row = self.__pdo_connect.select(cols, self.table, where, order, 0, 1)
            return row
        except Exception as e:
            self.__exception(e)

    def get_rows(self, where={},order={}, offset=0, limit=100, cols=[]):
        try:
            rows = self.__pdo_connect.select(cols, self.table, where, order, offset, limit)
            if not rows:
                return []
            return rows
        except Exception as e:
            self.__exception(e)

    def get_by_page(self, where, order={}, page=1, limit=100, cols=[]):

        offset = (page-1)*limit
        if offset<0:
            offset = 0
        try:
            rows = self.__pdo_connect.select(cols, self.table, where, order, offset, limit)
            if not rows:
                return []
            return rows
        except Exception as e:
            self.__exception(e)

    def num(self, where={}):

        try:
            num = self.__pdo_connect.count(self.table, where)
            return num
        except Exception as e:
            self.__exception(e)

    def get_all_items(self,where={},order={},page=1,limit=100,cols=[]):
        try:
            ret_data = {}
            ret_data["total"] = self.num(where)
            ret_data["items"]  = self.get_by_page(where,order,page,limit,cols)
            ret_data["current_total"] = len(ret_data["items"])
            return ret_data
        except Exception as e:
            self.__exception(e)